# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.utils.encoding import smart_unicode

from async import async_job
from common.channel.db import scan_repeat_no
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError, RepeatError, RepeatNotifyError

_LOGGER = track_logging.getLogger(__name__)

# https://gw.支付域名.com/create?time=unix_time&sign=签名串
_GATEWAY = 'https://gw.knwop.com/create?time={}&sign={}'
# https://rg.支付域名.com/api/query-order/商户号/商户Token后8位?flash_id=订单号
_QUERY_GATEWAY = 'https://rg.knwop.com/api/query-order/{}/{}?flash_id={}'

APP_CONF = {
    'KS': {
        'API_KEY': '35a19462-e931-4e18-9005-085788fff78a'
    },
    'ZSQP': {
        'API_KEY': '9382f0b8-9476-4a7a-a13a-3902a289e944'
    },
    'TTQP': {
        'API_KEY': '8818e211-3f58-4117-90de-972286260156'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, key):
    """ 生成下单签名 """
    s = '{}{}{}'.format(p_data, int(time.time()), key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    return sign


def _get_pay_type(type):
    if type == 'qq':
        return 'qqpay'
    elif type == 'alipay':
        return 'alipay'
    elif type == 'wxpay':
        return 'wxpay'
    elif type == 'jd':
        return 'jdpay'
    elif type == 'yunshanfu':
        return 'cloudflashpay'
    elif type == 'unionpay':
        return 'unionpay'
    else:
        return 'unionpay'


def verify_notify_sign(params, json, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(json.encode('utf8'), params['time'], key)
    m = hashlib.md5()
    m.update(s)
    calculated_sign = m.hexdigest().lower()
    if sign != calculated_sign:
        _LOGGER.info("grouppay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    """ 创建订单 """
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    metadata = info.get('metadata', '')
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(pay.id)),
        ('notify_url', '{}/pay/api/{}/grouppay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("bill_price", '%.2f' % pay_amount),
        ("payment", _get_pay_type(service)),
        ("info", {
            "device_type": user_info.get('device_type') or 'android',
            "device_id": user_info.get('device_id') or 'IMEI00000001111112222222',
            "device_ip": user_info.get('device_ip') or '171.212.112.44',
            "player_id": str(pay.user_id),
            "metadata": metadata
        }),
    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, api_key)
    gate_url = _GATEWAY.format(ts, sign)
    _LOGGER.info('grouppay brefore data: %s, %s', p_data, gate_url)
    headers = {'Content-type': 'application/json'}
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=5)
    _LOGGER.info('grouppay rsp data: %s\n%s', str(pay.id), response.text)
    data = json.loads(response.text)
    trade_id = data.get('trade_id')
    if not trade_id:
        order_db.fill_third_id(pay.id, trade_id)
    if metadata:
        return {'charge_info': data['pay_url'], 'is_metadata': 1}
    return {'charge_info': data['pay_url']}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("grouppay notify data: %s", data)
    _LOGGER.info("grouppay notify body: %s", request.body)
    verify_notify_sign(data, smart_unicode(request.body), api_key)
    data = json.loads(smart_unicode(request.body))
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('grouppay event does not contain pay ID')

    trade_status = int(data['status'])
    trade_no = data['trade_id']
    total_fee = float(data['receipt_amount'])
    trade_repeat = data.get('repeat_pay', False)

    if trade_repeat:
        alipay_no = data.get('upstream_order')
        scan_repeat_no('alipay', pay_id, trade_no, alipay_no, total_fee)
        raise RepeatError('grouppay trade_repeat : %s' % pay_id)

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise RepeatNotifyError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
        'discount': discount,
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 10000:
        _LOGGER.info('grouppay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    api_key = _get_api_key(app_id)
    pay_id = pay_order.id
    url = _QUERY_GATEWAY.format(app_id, api_key[-8:], pay_id)
    _LOGGER.info('grouppay brefore data: %s', url)
    headers = {'Content-type': 'application/json'}
    response = requests.get(url, headers=headers, timeout=3)
    _LOGGER.info('grouppay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['status']
        total_fee = float(data['receipt_amount'])
        trade_no = pay_order.third_id
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        """
        status枚举数	含义
        -1	下单失败（可能因为上游原因、或者网络原因、或者商户请求有问题）
        0	已下单
        1	已支付，正在回调
        2	已回调，交易完成
        """
        if trade_status in [1, 2]:
            # check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('grouppay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
